package name.jiaosha.air.system.dao.impl;

import name.jiaosha.air.constant.DocID;
import name.jiaosha.air.system.dao.IDocIDFactoryDao;
import name.jiaosha.air.system.domain.DocIDFactory;

import org.springframework.stereotype.Repository;

import com.ali8ba.common.AliUtil;
import com.ali8ba.dao.JpaDao;

@Repository
public class DocIDFactoryDao extends JpaDao<DocIDFactory, Integer> implements
		IDocIDFactoryDao {

	@Override
	public String getDocIDByComIdAndType(Integer comId, DocID docID) {

		String jpql = "SELECT d FROM DocIDFactory d where d.comId=?1 and d.typeName=?2 ";

		DocIDFactory docIDFactory = this.findForObject(jpql, comId,
				docID.toString());
		String lastDocID = null;
		String day = AliUtil.getCurrentDate("-");
		int num = 1;
		if (docIDFactory != null) {

			lastDocID = docIDFactory.getLastDocID();

			if (day.equals(lastDocID.substring(0, 9))) {
				num = docIDFactory.getLastNum() + 1;

			}
			lastDocID = day + num;
			docIDFactory.setLastNum(num);
			docIDFactory.setLastDocID(lastDocID);
			this.saveOrUpdate(docIDFactory);
			return lastDocID;
		} else {

			docIDFactory = new DocIDFactory();
			docIDFactory.setComId(comId);
			docIDFactory.setTypeName(docID.toString());

			lastDocID = day + num;
			docIDFactory.setLastNum(num);
			docIDFactory.setLastDocID(lastDocID);
			this.save(docIDFactory);

			return lastDocID;
		}

	}

}
